package com.woniu51.websocket.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu51.websocket.domain.Dashboard;
import com.woniu51.websocket.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author 杨光
 * @date 2022年04月12日 15:34
 */
@Component
@ServerEndpoint("/dashboard")
@CrossOrigin
public class WebSocketController {

    @Autowired
    private WebSocketService webSocketService;


    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        String str = "abc";
        Field value = str.getClass().getDeclaredField("value");
        value.setAccessible(true);
        char[] ch = (char[])value.get(str);
        System.out.println(value.getType().getSimpleName());
        ch[2]='d';

        System.out.println(str);

    }


    private static final CopyOnWriteArrayList<Session> sessionList = new CopyOnWriteArrayList();//线程安全的arrayList

    //1.连接创建成功执行的回调方法
    @OnOpen
    public void open(Session session){
        System.out.println("有新用户连接:"+session);
        sessionList.add(session);
    }

    //2.连接关闭时候执行的方法
    @OnClose
    public void close(Session session){
        System.out.println("有用户断开连接:"+session);
        Iterator<Session> iterator = sessionList.iterator();
        while(iterator.hasNext()){
            Session next = iterator.next();
            if(next==session){
                iterator.remove();
                break;
            }
        }
    }

    //3.出现错误时候执行的方法
    @OnError
    public void error(Session session,Throwable t){
        System.out.println("有用户通信异常");
    }

    //4.消息到达时候执行的方法
    @OnMessage
    public void message(String msg){
//        for (Session session : this.sessionList) {
//            try {
//                session.getBasicRemote().sendText("msg:"+new Date());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }


    }

    @Scheduled(fixedRate = 5000)
    public void schedule() throws JsonProcessingException {
        System.out.println("schedule:"+new Date());
        List<Dashboard> allDashboard = findAllDashboard();
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(allDashboard);
//        System.out.println("json:"+json);
        System.out.println("sessionList size:"+sessionList.size());
        System.out.println("sessionList :"+sessionList);
        for (Session session : sessionList) {
            try {
                System.out.println("session:"+session);
                session.getBasicRemote().sendText(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public List<Dashboard> findAllDashboard(){
        List<Dashboard> list = webSocketService.findAllDashboard();
        return list;
    }
}
